import React, { useState, useEffect } from 'react';
import { Select, Input, Button, Form, Row, Col, Checkbox, message, Modal } from 'antd';
import { getAllModes,getAllCycles, getModeSetting, saveModeSetting,getAllJyr, getBkInfo } from '../../service/apis/qx-cycle';
import { YqTypes, QxCycleMode, StockType } from '../../service/config';
import './index.css';
import { size } from 'lodash';

const { Option } = Select;

const ConfigurationPage = () => {
  const [cycles, setCycles] = useState([]);
  const [modes, setModes] = useState([]);
  const [selectedCycle, setSelectedCycle] = useState(null);
  const [enabledTypes, setEnabledTypes] = useState({});
  const [form] = Form.useForm();
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [tradeDays, setTradeDays] = useState([]);
  const [selectedTradeDay, setSelectedTradeDay] = useState(null);
  const [boards, setBoards] = useState([]);
  const [dpInfo, setDpInfo] = useState(null);
  const [selectedBoard, setSelectedBoard] = useState(null);
  const [selectedYqType, setSelectedYqType] = useState(null);

  const fieldsToSave = [
     'bk_zqxy_str', 'bk_kqxy_str', 'bk_kpyj_str', 'bk_high_zqxy_str', 
     'bk_high_kqxy_str', 'bk_high_kp_yj_str', 'bk_qd_str', 
     'dp_zqxy_str', 'dp_kqxy_str', 'dp_kpyj_str', 'dp_zt_zqxy_str', 
     'dp_zt_kqxy_str', 'dp_zt_kp_yj_str', 'dp_db_zqxy_str', 'dp_high_zqxy_str', 
     'dp_high_kqxy_str', 'dp_high_kp_yj_str','dp_db_kqxy_str', 
     'dp_db_kp_yj_str', 'dp_qd_str', 'dp_sz_num_str', 
     'dp_xd_num_str', 'dp_zt_num_str', 'dp_dt_num_str', 'dp_fb_value_str'
  ];

  const formatDate = (date) => {
    // 使用 toLocaleDateString 方法将日期格式化为 'YYYY-MM-DD'
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  };

  const toCamelCase = (str) => {
    return str.replace(/_(\w)/g, (_, c) => c.toUpperCase());
  };

  useEffect(() => {
    getAllCycles().then(data => {
      setCycles(data);
    }).catch(error => console.error('Error fetching cycle data:', error));

    getAllJyr().then(data => {
      setTradeDays(data.map(item => formatDate(new Date(item))));
    }).catch(error => console.error('Error fetching jyr data:', error));
  }, []);

  const handleCycleChange = async (cycle) => {
    setSelectedCycle(cycle);
    getAllModes({ cycle_code:cycle.cycle_code,bk_jiezou:cycle.bk_jiezou}).then(data => {
      setModes(data);
    }).catch(error => console.error('Error fetching monitor data:', error));
    getModeSetting({ cycle_code:cycle.cycle_code,bk_jiezou:cycle.bk_jiezou}).then(setting => {
      const formData = {};
      const enabledTypesData = {};
      if (setting == null) {
        setEnabledTypes(enabledTypesData);
        form.setFieldsValue(formData);
        return;
      }
        
      const groupedSetting = setting.reduce((acc, item) => {
        acc[item.yq_type] = item;
        return acc;
      }, {});

      Object.keys(YqTypes).forEach(typeKey => {
        const typeSetting = groupedSetting[typeKey];
        if (typeSetting) {
          enabledTypesData[typeKey] = true;
          formData[`${typeKey}-enabled`] = true;
          fieldsToSave.forEach(key => {
            if (typeSetting[key] && typeof typeSetting[key] === 'string' && typeSetting[key].includes(',')) {
              const [start, end] = typeSetting[key].split(',');
              formData[`${typeKey}-${key}-start`] = start;
              formData[`${typeKey}-${key}-end`] = end;
              formData[`${typeKey}-${key}-enabled`] = true;
            } else {
              formData[`${typeKey}-${key}-start`] = '';
              formData[`${typeKey}-${key}-end`] = '';
              formData[`${typeKey}-${key}-enabled`] = false;
            }
          });
        } else {
          enabledTypesData[typeKey] = false;
          formData[`${typeKey}-enabled`] = false;
        }
      });

      setEnabledTypes(enabledTypesData);
      form.setFieldsValue(formData);
    });
  };

  const handleSave = async () => {
    debugger
    const values = await form.validateFields();
    const dataToSave = {
      cycle_code: selectedCycle.cycle_code,
      bk_jiezou: selectedCycle.bk_jiezou,
    };
    Object.keys(YqTypes).forEach(typeKey => {
      if (enabledTypes[typeKey]) {
        const typeData = {};
        typeData['qx_cycle_mode'] = values[`${typeKey}-qx_cycle_mode`];
        fieldsToSave.forEach(key => {
          if (values[`${typeKey}-${key}-enabled`]) {
            typeData[key] = `${values[`${typeKey}-${key}-start`] || ''},${values[`${typeKey}-${key}-end`] || ''}`;
          } else {
            typeData[key] = '';
          }
        });
        dataToSave[typeKey] = typeData;
      } else {
        dataToSave[typeKey] = {};
      }
    });
    saveModeSetting(dataToSave).then(() => {
      message.success('保存成功');
    }).catch(() => {
      message.error('保存失败');
    });
  };

  const handleCheckboxChange = (typeKey, checked) => {
    setEnabledTypes(prevState => ({
      ...prevState,
      [typeKey]: checked
    }));
    form.setFieldsValue({ [`${typeKey}-enabled`]: checked });
  };

  const renderField = (label, key, typeKey) => (
    <Form.Item>
      <Row gutter={5}>
        <Col span={10}>
          <Form.Item style={{fontSize:'16px'}} name={`${typeKey}-${key}-enabled`} valuePropName="checked" noStyle>
            <Checkbox
              onChange={(e) => {
                form.setFieldsValue({ [`${typeKey}-${key}-enabled`]: e.target.checked });
                form.validateFields([`${typeKey}-${key}-start`, `${typeKey}-${key}-end`]);
              }}
            >
              {label}
            </Checkbox>
          </Form.Item>
        </Col>
        <Col span={7}>
          <Form.Item
            shouldUpdate={(prevValues, currentValues) => prevValues[`${typeKey}-${key}-enabled`] !== currentValues[`${typeKey}-${key}-enabled`]}
            noStyle
          >
            {({ getFieldValue }) => (
              <Form.Item
                name={`${typeKey}-${key}-start`}
                noStyle
                rules={[{ required: getFieldValue(`${typeKey}-${key}-enabled`), message: '起始值不能为空' }]}
              >
                <Input placeholder="起始值" disabled={!getFieldValue(`${typeKey}-${key}-enabled`)} />
              </Form.Item>
            )}
          </Form.Item>
        </Col>
        <Col span={7}>
          <Form.Item
            shouldUpdate={(prevValues, currentValues) => prevValues[`${typeKey}-${key}-enabled`] !== currentValues[`${typeKey}-${key}-enabled`]}
            noStyle
          >
            {({ getFieldValue }) => (
              <Form.Item
                name={`${typeKey}-${key}-end`}
                noStyle
                rules={[{ required: getFieldValue(`${typeKey}-${key}-enabled`), message: '结束值不能为空' }]}
              >
                <Input placeholder="结束值" disabled={!getFieldValue(`${typeKey}-${key}-enabled`)} />
              </Form.Item>
            )}
          </Form.Item>
        </Col>
      </Row>
    </Form.Item>
  );

  const showModal = () => {
    setIsModalVisible(true);
  };

  const handleTradeDayChange = (value) => {
    setSelectedTradeDay(value);
    getBkInfo({ jyr: value }).then(data => {
      setBoards(data.bks);
      setDpInfo(data.dp);
    }).catch(error => console.error('Error fetching board info:', error));
  };

  const handleBoardChange = (value) => {
    const board = boards.find(b => b.code === value);
    setSelectedBoard(board);
  };

  const handleYqTypeChange = (value) => {
    setSelectedYqType(value);
  };
 
  const handleModalOk = () => {
    if (selectedBoard && selectedYqType) {
      debugger
      const formData = {};
      const updatedEnabledTypes = { ...enabledTypes, [selectedYqType]: true };
      setEnabledTypes(updatedEnabledTypes);
      formData[`${selectedYqType}-enabled`] = true;
      fieldsToSave.forEach(key => {
        if(key.startsWith('dp')) {
          const fieldKey = toCamelCase(key.replace('_str', '').replace('dp_', ''));
          formData[`${selectedYqType}-${key}-start`] = dpInfo[fieldKey];
          formData[`${selectedYqType}-${key}-end`] = dpInfo[fieldKey];
          formData[`${selectedYqType}-${key}-enabled`] = true;
        }else{
          const fieldKey = toCamelCase(key.replace('_str', '').replace('bk_', ''));
          formData[`${selectedYqType}-${key}-start`] = selectedBoard[fieldKey];
          formData[`${selectedYqType}-${key}-end`] = selectedBoard[fieldKey];
          formData[`${selectedYqType}-${key}-enabled`] = true;
        }
      });
      form.setFieldsValue(formData);
      setIsModalVisible(false);
    } else {
      message.error('请选择板块和预期设置');
    }
  };

  const handleModalCancel = () => {
    setIsModalVisible(false);
  };

  return (
    <div className="configuration-page">
      <Row>
        <Col span={8}>
          <Select
            style={{ width: 200 }}
            onChange={(id) => {
              const cycle = cycles.find(m => m.id === id);
              handleCycleChange(cycle);
            }}
            placeholder="情绪周期阶段"
          >
            {cycles.map(cycle => (
              <Option key={cycle.id} value={cycle.id}>{cycle.name}</Option>
            ))}
          </Select>
        </Col>
        {/* <Col className="mode-remark" span={16}>
          {selectedMode && (
            <Row gutter={20}>
              <Col>
                <p>适用周期: {QxCycleMode[selectedMode.qx_cycle_code]}</p>
              </Col>
              <Col>
                <p>适用板块级别: {selectedMode.bk_level}</p>
              </Col>
              <Col>
                <p>适用股票类型: {StockType[selectedMode.stock_type]}</p>
              </Col>
              <Col>
                <p>备注: {selectedMode.remark}</p>
              </Col>
            </Row>
          )}
        </Col> */}
      </Row>

      {selectedCycle && (
        <Form form={form} layout="vertical">
          <Row gutter={10}>
            {Object.keys(YqTypes).map(typeKey => (
              <Col key={typeKey} className='form-col' span={24}>
                <Checkbox
                  checked={enabledTypes[typeKey]}
                  onChange={(e) => handleCheckboxChange(typeKey, e.target.checked)}
                >
                  <h3 className="section-title">{YqTypes[typeKey]}</h3>
                </Checkbox>
                {enabledTypes[typeKey] && (
                  <>
                  <Row gutter={10} align="middle">
                    <Col span={6}>
                      <h3 className="section-title">模式选择</h3>
                    </Col>
                    <Col span={6} style={{ height: '40px'}}>
                      <Form.Item name={`${typeKey}-qx_cycle_mode`} rules={[{ required: true, message: '请选择模式' }]}>
                        <Select placeholder="请选择模式">
                          {modes.map(mode => (
                            <Option key={mode.code} value={mode.code}>{mode.name}</Option>
                          ))}
                        </Select>
                      </Form.Item>
                    </Col>
                  </Row>
                  <Row gutter={10}>
                    <Col span={6}>
                      <h3 className="section-title">大盘</h3>
                      {renderField('强度(大盘)', 'dp_qd_str', typeKey)}
                      {renderField('上涨家数', 'dp_sz_num_str', typeKey)}
                      {renderField('下跌家数', 'dp_xd_num_str', typeKey)}
                      {renderField('涨停家数', 'dp_zt_num_str', typeKey)}
                      {renderField('跌停家数', 'dp_dt_num_str', typeKey)}
                      {renderField('封板资金', 'dp_fb_value_str', typeKey)}
                      {renderField('强度(板块)', 'bk_qd_str', typeKey)}
                    </Col>
                    <Col span={6}>
                      <h3 className="section-title">总体</h3>
                      {renderField('赚钱效应(大盘)', 'dp_zqxy_str', typeKey)}
                      {renderField('亏钱效应(大盘)', 'dp_kqxy_str', typeKey)}
                      {renderField('开盘溢价(大盘)', 'dp_kpyj_str', typeKey)}
                      {renderField('赚钱效应(板块)', 'bk_zqxy_str', typeKey)}
                      {renderField('亏钱效应(板块)', 'bk_kqxy_str', typeKey)}
                      {renderField('开盘溢价(板块)', 'bk_kpyj_str', typeKey)}
                    </Col>
                    <Col span={6}>
                      <h3 className="section-title">核心</h3>
                      {renderField('赚钱效应(大盘)', 'dp_high_zqxy_str', typeKey)}
                      {renderField('亏钱效应(大盘)', 'dp_high_kqxy_str', typeKey)}
                      {renderField('开盘溢价(大盘)', 'dp_high_kp_yj_str', typeKey)}
                      {renderField('赚钱效应(板块)', 'bk_high_zqxy_str', typeKey)}
                      {renderField('亏钱效应(板块)', 'bk_high_kqxy_str', typeKey)}
                      {renderField('开盘溢价(板块)', 'bk_high_kp_yj_str', typeKey)}
                    </Col>
                    <Col span={6}>
                      <h3 className="section-title">涨停/断板</h3>
                      {renderField('赚钱效应', 'dp_zt_zqxy_str', typeKey)}
                      {renderField('亏钱效应', 'dp_zt_kqxy_str', typeKey)}
                      {renderField('开盘溢价', 'dp_zt_kp_yj_str', typeKey)}
                      {renderField('赚钱效应', 'dp_db_zqxy_str', typeKey)}
                      {renderField('亏钱效应', 'dp_db_kqxy_str', typeKey)}
                      {renderField('开盘溢价', 'dp_db_kp_yj_str', typeKey)}
                    </Col>
                  </Row>
                  </>
                )}
              </Col>
            ))}
          </Row>
          <Button type="primary" onClick={handleSave} style={{ marginBottom: 10 }}>
            保存
          </Button>
          <Button type="default" onClick={showModal} style={{ marginBottom: 10, marginLeft: 10 }}>
            填充样本数据
          </Button>
        </Form>
      )}

      <Modal title="填充样本数据" visible={isModalVisible} onOk={handleModalOk} onCancel={handleModalCancel}>
        <Form layout="vertical">
          <Form.Item label="交易日">
            <Select onChange={handleTradeDayChange} placeholder="请选择交易日">
              {tradeDays.map(day => (
                <Option key={day} value={day}>{day}</Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item label="板块" style={{ display: selectedTradeDay ? 'block' : 'none' }}>
            <Select onChange={handleBoardChange} placeholder="请选择板块">
              {boards.map(board => (
                <Option key={board.code} value={board.code}>{board.name}</Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item label="预期设置" style={{ display: selectedTradeDay ? 'block' : 'none' }}>
            <Select onChange={handleYqTypeChange} placeholder="请选择预期设置">
              {Object.keys(YqTypes).map(typeKey => (
                <Option key={typeKey} value={typeKey}>{YqTypes[typeKey]}</Option>
              ))}
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default ConfigurationPage;